import React, {useEffect, useState} from 'react'
import {Button, Card, Form, Input, message, Upload, Image} from 'antd'
import {createApi, modifyOne} from '../../services/products'
import {useNavigate, useParams} from "react-router-dom";
import { PlusOutlined } from '@ant-design/icons';
import {serverUrl} from '../../utils/config'
import {Editor, EditorState} from 'draft-js';
import 'draft-js/dist/Draft.css';

const getBase64 = file =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });


function Edit(props) {
    const [form] = Form.useForm()
    const navigate = useNavigate();
    const {id} = useParams(); // 获取路由参数
    const [loading, setLoading] = useState(false);
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [fileList, setFileList] = useState([])
    const [editorState, setEditorState] = React.useState(
        () => EditorState.createEmpty(),
    );

    // 如果是编辑模式，获取商品详情
    useEffect(() => {
        if (id && id !== 'new') {
            // 这里需要获取商品详情的 API
            // 暂时用模拟数据
            console.log('获取商品详情，ID:', id);
            // getProductDetail(id).then(data => {
            //     setProductData(data);
            //     form.setFieldsValue(data);
            // });
        }
    }, [id]);

    // 在onFinish前添加代码
    const content = editorState.getCurrentContent().getPlainText();
    form.setFieldsValue({
        content: content
    });

    // 处理表单提交
    const onFinish = async (values) => {
        console.log("表单提交的值：", values)

        try {
            setLoading(true);
            let response;

            if (id && id !== 'new') {
                // 修改模式
                response = await modifyOne(id, values);
                if (response) {
                    message.success('商品修改成功');
                } else {
                    message.error('修改失败，请重试');
                }
            } else {
                // 新增模式
                response = await createApi(values);
                if (response) {
                    message.success('商品保存成功');
                } else {
                    message.error('保存失败，请重试');
                }
            }

            if (response) {
                // 跳转到商品列表页
                navigate('/admin/products');
            }
        } catch (error) {
            console.error('保存商品失败:', error);
            message.error('保存失败，请重试');
        } finally {
            setLoading(false);
        }
    }

    // 处理表单提交失败
    const onFinishFailed = (err) => {
        console.log('表单验证失败：', err)
        message.error('请检查输入内容是否正确')
    }

    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </button>
    );

    const handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setPreviewImage(file.url || file.preview);
        setPreviewOpen(true);
    };
    const handleChange = (info) => {
        console.log('Upload change info:', info)

        //始终更新 fileList
        setFileList(info.fileList)

        if (info.file.status === 'uploading') {
            setLoading(true)
            return
        }

        if (info.file.status === 'done') {
            setLoading(false)
            message.success(`${info.file.name} 上传成功`)

            const uploadedFile = info.file.response
            if (uploadedFile && uploadedFile.info) {
                const fileUrl = uploadedFile.info
                form.setFieldsValue({
                    coverImg: fileUrl
                })
                console.log('封面图片URL已设置:', fileUrl)
            }
            setPreviewImage(info.file.response.info)
        }

        if (info.file.status === 'error') {
            setLoading(false)
            message.error(`${info.file.name} 上传失败，请重试`)
        }
    }




    return (
        <Card title={id && id !== 'new' ? "修改商品" : "新增商品"}>
            <Form
                form={form}
                name="productEdit"
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
            >
                <Form.Item
                    label="商品名称"
                    name="name"
                    rules={[{required: true, message: '请输入商品名称'}]}
                >
                    <Input placeholder="请输入商品名字"/>
                </Form.Item>

                <Form.Item
                    label="商品价格"
                    name="price"
                    rules={[
                        {required: true, message: '请输入商品价格'},
                        {type: "number", min: 0, message: "价格必须大于等于0"}
                    ]}
                >
                    <Input
                        type="number"
                        placeholder="请输入商品价格"
                        addonAfter="美元"
                        onChange={(e) => {
                            const value = parseFloat(e.target.value)
                            if (!isNaN(value) && value >= 0) {
                                form.setFieldsValue({price: value});
                            }
                        }}
                    />
                </Form.Item>

                {/*// 这里应该有个图片上传*/}
                <Form.Item>
                    <Upload
                        action={serverUrl+'/api/v1/common/file_upload'}
                        listType="picture-card"
                        fileList={fileList}
                        onPreview={handlePreview}
                        onChange={(info)=>handleChange(info)}
                    >
                        {fileList.length >= 1 ? null : uploadButton}
                    </Upload>
                    {previewImage && (
                        <Image
                            wrapperStyle={{ display: 'none' }}
                            preview={{
                                visible: previewOpen,
                                onVisibleChange: visible => setPreviewOpen(visible),
                                afterOpenChange: visible => !visible && setPreviewImage(''),
                            }}
                            src={serverUrl+previewImage}
                        />
                    )}
                </Form.Item>
                {/*// 这里应该有个富文本编辑器*/}
                <Form.Item>
                    <div style={{ marginBottom: '16px' }}>
                        <label style={{ display: 'block', marginBottom: '8px', fontWeight: '500' }}>商品描述：</label>
                        <Editor
                            editorState={editorState}
                            onChange={setEditorState}
                            placeholder="请输入商品描述"
                            style={{
                                minHeight: '200px',
                                border: '1px solid #d9d9d9',
                                borderRadius: '4px',
                                padding: '8px',
                                backgroundColor: '#fff'
                            }}
                        />
                    </div>
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit" loading={loading}>
                        保存
                    </Button>
                    <Button
                        style={{margin: "1rem"}}
                        type="primary" danger
                        onClick={() => navigate('/admin/products')}
                    >
                        取消
                    </Button>
                </Form.Item>
            </Form>
        </Card>
    )
}

export default Edit
